package com.domino.server.user;

import java.util.Map;
import java.util.logging.Logger;


public class FacebookGraphImpl implements FaceBookGraph {
	
	Logger LOG = Logger.getLogger(getClass().getCanonicalName());
	
	private static final String GRAPH_API_URL = "http://graph.facebook.com/";
	private static final String BOOKMARK_API_URL = "https://api.facebook.com/method/dashboard.incrementCount?access_token=";
	private static final String RESET_BOOKMARK_API_URL = "https://api.facebook.com/method/dashboard.setCount?count=0&access_token=";

	//private static final String ACCESS_TOKEN_URL_TEMPLATE = 
	//	GRAPH_API_URL + "/oauth/access_token?client_id=%s&redirect_uri=%s&client_secret=%s&code=%s";

	String appId;
	String secret;

	public FacebookGraphImpl(String appId, String secret) {
		this.appId = appId;
		this.secret = secret;
	}

	/* (non-Javadoc)
	 * @see com.domino.server.user.FaceBookGraph#getName(java.lang.String)
	 */
	@Override
	public String getName(String id) {
		Map<String,String> map = getPlayerInfoResource(id);
		if (map==null) {
			return null;
		}
		return map.get("name");
	}

	/*public String getAccessToken(String redirectUrl, String code) {
		if (code==null) {
			throw new IllegalStateException("Code cannot be null");
		}
		String accessToken = WebContentUtil.getPageContent(String.format(ACCESS_TOKEN_URL_TEMPLATE, appId, redirectUrl, secret, code));
		return accessToken;
	}*/

	/* (non-Javadoc)
	 * @see com.domino.server.user.FaceBookGraph#getMe(java.lang.String)
	 */
	@Override
	public Map<String, String>  getMe(String accessToken) {
		String content = WebContentUtil.getPageContent(GRAPH_API_URL + "me?access_token="+accessToken);
		return JSonUtil.decode(content);
	}
	
	private Map<String, String> getPlayerInfoResource(String id) {
		String content = WebContentUtil.getPageContent(GRAPH_API_URL + id);
		return JSonUtil.decode(content);
	}
	
	/* (non-Javadoc)
	 * @see com.domino.server.user.FaceBookGraph#getCookieName()
	 */
	@Override
	public String getCookieName() {
		return "fbs_" + FacebookApplication.APP_ID;
	}

	/* (non-Javadoc)
	 * @see com.domino.server.user.FaceBookGraph#updateBookmark(java.lang.String)
	 */
	@Override
	public void updateBookmark(String accessToken) {
		if (accessToken!=null) {
			String content = WebContentUtil.getPageContent(BOOKMARK_API_URL
				+ accessToken);
			LOG.info("Updated bookmark: " + content);
		}
	}

	@Override
	public void resetBookmark(String accessToken) {
		if (accessToken!=null) {
			String content = WebContentUtil.getPageContent(RESET_BOOKMARK_API_URL
				+ accessToken);
			LOG.info("Reseted bookmark: " + content);
		}
	}

}
